package cn.tedu._07springaop.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Array;
import java.util.Arrays;

@Aspect
@Component
public class LogAspect {
    @Before(value = "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))")
    public void beforeMethod(JoinPoint joinPoint){

        String name = joinPoint.getSignature().getName();

        String args = Arrays.toString(joinPoint.getArgs());

        System.out.println("[前置通知]:"+ name +"方法开始，参数为:" + args);
    }

    @AfterReturning(value = "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))", returning = "r")
    public void afterReturningMethod(JoinPoint joinPoint, Object r){
        String name = joinPoint.getSignature().getName();
        System.out.println("[返回通知]:" + name + "方法结束,结果为:"+ r);
    }

    @After(value = "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))")
    public void afterMethod(JoinPoint joinPoint){
        String name = joinPoint.getSignature().getName();
        System.out.println("[后置通知]:" + name + "方法彻底结束");
    }

    @AfterThrowing(value = "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))", throwing = "ex")
    public void afterThrowingMethod(JoinPoint joinPoint, Throwable ex){
        String name = joinPoint.getSignature().getName();
        String message = ex.getMessage();
        System.out.println("[异常通知]:" + name + "方法异常:" + message);

    }

    @Around(value = "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))")
    public Object aroundMethod(ProceedingJoinPoint joinPoint){
        Object result = null;
        try{
            System.out.println("111-前置通知");

            result = joinPoint.proceed();

            System.out.println("111-返回通知");
        } catch (Throwable e) {
            System.out.println("111-异常通知");

            throw new RuntimeException(e);
        }finally {
            System.out.println("111-后置通知");
        }

        return result;
    }
}
